<?php
/**
 * Create by Phpstorm
 * User: Peco
 * Date: 2019/11/27
 * Time: 15:38
 */

namespace App\Repositories;

use App\Models\AuctionGoodsInfo;
use App\Models\Carrier;
use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\Order;
use App\Models\Region;
use App\Models\User;
use App\Models\UserAddress;
use App\Models\UserIncreaseamountRecord;
use App\Models\UserIntegralSummary;
use App\Models\UserMailing;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

/**
 * 订单数据
 * Class OrderRepository
 * @package App\Repositories
 */
class OrderRepository extends BaseRepositories
{
    /**
     * @var User 注入的 model
     */
    protected $user;

    /**
     * @var UserAddress 注入的 model
     */
    protected $userAddress;

    /**
     * @var Region 注入的 model
     */
    protected $region;

    /**
     * @var AuctionGoodsInfo 注入的 model
     */
    protected $auctionGoodsInfo;

    /**
     * @var GoodsSku 注入的 model
     */
    protected $goodsSku;

    /**
     * @var Order 注入的 model
     */
    protected $order;

    /**
     * @var Goods 注入的 model
     */
    protected $goods;

    /**
     * @var UserMailing 注入的 model
     */
    protected $userMailing;

    /**
     * @var UserIncreaseamountRecord 注入的 model
     */
    protected $userIncreaseAmountRecord;

    /**
     * @var UserIntegralSummary 注入的 model
     */
    protected $userIntegralSummary;

    /**
     * @var Carrier 注入的 model
     */
    protected $carrier;

    /**
     * OrderRepository constructor.
     * @param User $user
     * @param UserAddress $userAddress
     * @param Region $region
     * @param AuctionGoodsInfo $auctionGoodsInfo
     * @param UserMailing $userMailing
     * @param GoodsSku $goodsSku
     * @param Order $order
     * @param Goods $goods
     * @param UserIncreaseamountRecord $userIncreaseAmountRecord
     * @param UserIntegralSummary $userIntegralSummary
     */
    public function __construct(User $user, UserAddress $userAddress,
                                Region $region, AuctionGoodsInfo $auctionGoodsInfo,
                                UserMailing $userMailing, GoodsSku $goodsSku,
                                Order $order, Goods $goods,
                                UserIncreaseamountRecord $userIncreaseAmountRecord,
                                UserIntegralSummary $userIntegralSummary, Carrier $carrier){
        $this->user = $user;
        $this->userAddress = $userAddress;
        $this->region = $region;
        $this->auctionGoodsInfo = $auctionGoodsInfo;
        $this->goodsSku = $goodsSku;
        $this->order = $order;
        $this->goods = $goods;
        $this->userMailing = $userMailing;
        $this->userIncreaseAmountRecord = $userIncreaseAmountRecord;
        $this->userIntegralSummary = $userIntegralSummary;
        $this->carrier = $carrier;
    }

    /**
     * 获取订单列表
     * @param array $data
     * @param int $limit
     * @return mixed
     */
    public function getOrderPageRepository(array $data, $limit = LIMIT_PAGE){
        $consignee = data_get($data, 'consignee');
        $createTime = data_get($data, 'createTime');
        $userName = data_get($data, 'userName');
        Arr::forget($data, 'consignee');
        Arr::forget($data, 'sourceType');
        Arr::forget($data, 'createTime');
        Arr::forget($data, 'userName');
        return $this->order
            ->when($createTime, function ($q)use($createTime){
                $q->where('createTime', '>=', $createTime);
            })
            ->when($userName, function ($q)use($userName){
                $q->where('userName', 'like', '%'.$userName.'%');
            })
            ->when($data, function ($q)use($data){
                $q->where($data);
            })
            ->orderByDesc('updateTime')
            ->paginate($limit);
    }

    /**
     * 获取订单详情
     * @param int $orderId
     * @return mixed
     */
    public function getOrderDetailRepository(int $orderId){
        return $this->order
            ->with(['items'=>function($q){
                $q->with(['goods', 'goodsSku']);
            }])
            ->findOrFail($orderId);
    }

    /**
     * 地域列表
     * @param int $parentId
     * @return mixed
     */
    public function regionListRepository(int $parentId){
        return $this->region
            ->where(['parent_id'=>$parentId])
            ->select(['id', 'areaname', 'parent_id'])
            ->orderBy('sort_order', 'asc')
            ->get();
    }

    /**
     * 获取物流公司
     * @return mixed
     */
    public function getCarrierListRepository(){
        return $this->carrier->get();
    }

    /**
     * 订单发货
     * @param array $datum
     * @return bool
     */
    public function deliverOrderRepository(array $datum){

        //生成事务
        DB::beginTransaction();
        try {

            foreach ($datum as $item){

                //获取物流数据 TODO 可首先查询
                $carrier = $this->carrier->findOrFail($item['carrierId']);
                $shipData = ['shipNo'=>$item['shipNo'],
                    'carrierName' => $carrier->carrierName,
                    'carrierNo'=> $carrier->carrierNo,
                    'carrierId'=> $item['carrierId']];
                $shipData = \GuzzleHttp\json_encode($shipData);

                //更新订单
                 $this->order
                    ->where('orderId', $item['orderId'])
                    ->update(['orderStatus'=>ORDER_GOODS_TO_BE_RECEIVED,
                        'deliverTime'=>Carbon::now(),
                        'carrierId'=> $item['carrierId'],
                        'shipData' => $shipData]);
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollback();
            $this->response->errorInternal($e->getMessage());exit;
        }
    }

    /**
     * 修改收货人信息
     * @param array $data
     * @return mixed
     */
    public function updateReceiverRepository(array $data){
        $order = $this->order->findOrFail($data['orderId']);

        //获取地址
        $region = $this->region
            ->whereIn('id', [$data['receiverProvince'],$data['receiverCity'],$data['receiverAddress']])
            ->get(['areaname'])
            ->toArray();//var_dump(data_get($region, '0'));exit;

        //生成json格式的数据包
        $fullAddress = data_get($region, '0.areaname').data_get($region, '1.areaname').data_get($region, '2.areaname').$data['receiverDetailAddress'];
        $address = \GuzzleHttp\json_encode([
            'address'       => $fullAddress,
            'zip'           => $data['zip'],
            'consignee'  => $data['consignee'],
            'mobile' => $data['phone'],
        ]);

        $order->address = $address;

        return $order->saveOrFail();
    }

}
